package com.neusoft.actor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.actor.dao.*;
import com.neusoft.actor.dto.CheckoutRequestWithClientDto;
import com.neusoft.actor.po.*;
import com.neusoft.actor.service.CheckoutRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CheckoutRequestServiceImpl implements CheckoutRequestService {

    @Autowired
    private CheckoutRequestDao checkoutRequestDao;
    @Autowired
    private BedDao bedDao;
    @Autowired
    private BedUsageDao bedUsageDao;
    @Autowired
    private ClientDao clientDao;
    @Autowired
    private CaretakerClientDao caretakerClientDao;

    @Override
    public ResponseBean<List<CheckoutRequest>> getAllCheckoutRequests() {
        List<CheckoutRequest> checkoutRequests = checkoutRequestDao.selectList(null);
        return new ResponseBean<>(checkoutRequests);
    }

    @Override
    public ResponseBean<CheckoutRequest> getCheckoutRequestById(Integer requestId) {
        CheckoutRequest checkoutRequest = checkoutRequestDao.selectById(requestId);
        if (checkoutRequest != null) {
            return new ResponseBean<>(checkoutRequest);
        } else {
            return new ResponseBean<>(404, "退住申请未找到");
        }
    }

    @Override
    public ResponseBean<Integer> addCheckoutRequest(CheckoutRequest checkoutRequest) {
        int result = checkoutRequestDao.insert(checkoutRequest);
        return new ResponseBean<>(result); // 返回插入成功的行数
    }

    @Override
    public ResponseBean<Integer> updateCheckoutRequest(CheckoutRequest checkoutRequest) {
        int result = checkoutRequestDao.updateById(checkoutRequest);
        return new ResponseBean<>(result); // 返回更新成功的行数
    }

    @Override
    public ResponseBean<Integer> deleteCheckoutRequest(Integer requestId) {
        int result = checkoutRequestDao.deleteById(requestId);
        return new ResponseBean<>(result); // 返回删除成功的行数
    }

    @Override
//    条件查询退住请求的客户信息 + 连接多表
    public ResponseBean<List<CheckoutRequestWithClientDto>> getCheckoutRequests(String clientName, String isSelfCare) {
        List<CheckoutRequestWithClientDto> result = checkoutRequestDao.getCheckoutRequestsByConditions(clientName, isSelfCare);
        if (result != null) {
            return new ResponseBean<>(result);
        } else {
            return new ResponseBean<>(404,"未找到");
        }
    }

    @Override
//    通过/不通过退住
    public ResponseBean<Integer> passCheckoutRequest(CheckoutRequest checkoutRequest) {
        Bed bed;
        Integer clientId = checkoutRequest.getClientId();
        Client client = clientDao.selectById(clientId);
        BedUsage bedUsage = bedUsageDao.selectOne(
                new QueryWrapper<BedUsage>().eq("usage_id", clientId).eq("is_current", 1)
        );
        if (bedUsage != null && client != null) {
            bedUsage.setIsCurrent(false);
            bedUsageDao.updateById(bedUsage);
            client.setActive(false);
            clientDao.updateById(client);
            Integer bedId = bedUsage.getBedId();
            bed = bedDao.selectById(bedId);
            if (bed != null && (checkoutRequest.getType().equals("正常退住") || checkoutRequest.getType().equals("死亡退住"))) {
                bed.setStatus("空闲");
                bedDao.updateById(bed);
            }
        }
        int result = checkoutRequestDao.updateById(checkoutRequest);
        return new ResponseBean<>(result);
    }

    @Override
//   健康管家查询自己服务客户的退住申请,可以根据姓名模糊查询
    public ResponseBean<List<CheckoutRequestWithClientDto>> getCheckoutRequestsByCareTakerId(Integer careTakerId, String clientName) {
        // 查询健康管家管理的所有客户ID，貌似可以直接调条件查询
        List<CaretakerClient> caretakerClients = caretakerClientDao.selectList(new QueryWrapper<CaretakerClient>().eq("caretaker_id", careTakerId));
        List<Integer> clientIds = caretakerClients.stream()
                .map(CaretakerClient::getClientId)
                .collect(Collectors.toList());

        // 如果没有客户，直接返回404
        if (clientIds.isEmpty()) {
            return new ResponseBean<>(404, "该健康管家没有客户");
        }

        // 查询所有客户的退住申请
        List<CheckoutRequestWithClientDto> allCheckoutRequests = new ArrayList<>();
        for (Integer clientId : clientIds) {
            List<CheckoutRequest> checkoutRequests = checkoutRequestDao.selectList(new QueryWrapper<CheckoutRequest>().eq("client_id", clientId));
            for (CheckoutRequest request : checkoutRequests) {
                Client client = clientDao.selectById(request.getClientId());
                if (client != null) {
                    CheckoutRequestWithClientDto dto = new CheckoutRequestWithClientDto();
                    dto.setRequestId(request.getRequestId());
                    dto.setClientName(client.getClientName());
                    dto.setClientId(request.getClientId());
                    dto.setIsSelfCare(client.getIsSelfCare());
                    dto.setRoomNumber(client.getRoomNumber());
                    dto.setAge(client.getAge());
                    dto.setType(request.getType());
                    dto.setReason(request.getReason());
                    dto.setCheckoutTime(request.getCheckoutTime());
                    dto.setStatus(request.getStatus());
                    dto.setRemark(request.getRemark());
                    allCheckoutRequests.add(dto);
                }
            }
        }

        // 如果提供了客户名称，则进行模糊查询
        if (clientName != null && !clientName.isEmpty()) {
            allCheckoutRequests = allCheckoutRequests.stream()
                    .filter(request -> request.getClientName().contains(clientName))
                    .collect(Collectors.toList());
        }

        // 返回结果
        if (!allCheckoutRequests.isEmpty()) {
            return new ResponseBean<>(allCheckoutRequests);
        } else {
            return new ResponseBean<>(404, "未找到符合条件的退住申请");
        }
    }
}